<template>
  <div>
    <el-form :model="queryParams"
             ref="queryForm"
             size="small"
             :inline="true"
             label-width="80px">
      <el-form-item label="股票名称"
                    prop="stockName">
        <el-input v-model="queryParams.stockName"
                  placeholder="请输入股票名称"
                  clearable
                  @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="mini"
                   @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"
                   size="mini"
                   @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="20">
      <el-col :span="8">
        <div class="grid-content bg-purple">
          <el-table :data="HJFS"
                    max-height="400"
                    size="small"
                    style="width: 100%">
            <el-table-column label="异动信息：火箭发射">
              <el-table-column prop="stockName"
                               label="股票名称">
              </el-table-column>

              <el-table-column prop="stockSymbol"
                               label="股票代码">
              </el-table-column>
              <el-table-column prop="count"
                               label="异动次数">
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content bg-purple-light">
          <el-table :data="DBMR"
                    max-height="400"
                    size="small"
                    style="width: 100%">
            <el-table-column label="异动信息: 大笔买入">
              <el-table-column prop="stockName"
                               label="股票名称">
              </el-table-column>

              <el-table-column prop="stockSymbol"
                               label="股票代码">
              </el-table-column>
              <el-table-column prop="count"
                               label="异动次数">
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content bg-purple-light">
          <el-table :data="KSFT"
                    max-height="400"
                    size="small"
                    style="width: 100%">
            <el-table-column label="异动信息: 快速反弹">
              <el-table-column prop="stockName"
                               label="股票名称">
              </el-table-column>

              <el-table-column prop="stockSymbol"
                               label="股票代码">
              </el-table-column>
              <el-table-column prop="count"
                               label="异动次数">
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <div class="checkbox-group-container">
      <el-checkbox-group v-model="checkList"
                         @change="handleChange"
                         class="checkbox-group">
        <el-checkbox label="8201">火箭发射</el-checkbox>
        <el-checkbox label="8202">快速反弹</el-checkbox>
        <el-checkbox label="8193">大笔买入</el-checkbox>
        <el-checkbox label="4">封涨停板</el-checkbox>
        <el-checkbox label="32">打开跌停板</el-checkbox>
        <el-checkbox label="64">有大买盘</el-checkbox>
        <el-checkbox label="8207">竞价上涨</el-checkbox>
        <el-checkbox label="8209">高开5日线</el-checkbox>
        <el-checkbox label="8211">向上缺口</el-checkbox>
        <el-checkbox label="8213">60日新高</el-checkbox>
        <el-checkbox label="8215">60日大幅上涨</el-checkbox>
        <el-checkbox label="8204">加速下跌</el-checkbox>
        <el-checkbox label="8203">高台跳水</el-checkbox>
        <el-checkbox label="8194">大笔卖出</el-checkbox>
        <el-checkbox label="8">封跌停板</el-checkbox>
        <el-checkbox label="16">打开涨停板</el-checkbox>
        <el-checkbox label="128">有大卖盘</el-checkbox>
        <el-checkbox label="8208">竞价下跌</el-checkbox>
        <el-checkbox label="8210">低开5日线</el-checkbox>
        <el-checkbox label="8212">向下缺口</el-checkbox>
        <el-checkbox label="8214">60日新低</el-checkbox>
        <el-checkbox label="8216">60日大幅下跌</el-checkbox>
      </el-checkbox-group>
    </div>

    <div>
      <el-table :data="paginatedData"
                size="small"
                style="width: 100%">
        <el-table-column prop="stockName"
                         label="股票名称"
                         width="180">
        </el-table-column>
        <el-table-column prop="stockSymbol"
                         label="股票代码"
                         width="180">
        </el-table-column>
        <el-table-column prop="changeType"
                         label="异动类型"
                         width="180">
        </el-table-column>
        <el-table-column prop="date"
                         :formatter="formatDate"
                         label="异动时间">
        </el-table-column>

        <el-table-column label="异动信息">
          <el-table-column label="信息"
                           :formatter="formatData"
                           prop="changeInfo">
          </el-table-column>
          <el-table-column label="价格"
                           :formatter="formatPrice"
                           prop="price">
          </el-table-column>
          <el-table-column label="涨跌幅"
                           :formatter="formatData"
                           prop="percent">
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <div class="block">
      <el-pagination background
                     style="margin-top: 20px;"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="stockChangeData.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>

export default {
  data () {
    return {
      checkList: ['8201', '8193', "8202", "4"],
      stockChangeData: [],
      paginatedData: [],  // 分页后在表格中显示的数据
      currentPage: 1,
      pageSize: 20,
      timer: null,  // 用于存储定时器引用
      queryParams: {
        orderByColumn: '',
        isAsc: '',
        stockName: '',
        stockSymbol: ''
      },
    };
  },
  created () {
    this.handleStockChangeData();
    this.startPolling();
  },
  beforeDestroy () {
    this.stopPolling();  // 组件销毁前清除定时器
  },
  // mounted () {
  //   this.formatData();
  // },
  computed: {
    // paginatedDataTable () {
    //   const start = (this.currentPage - 1) * this.pageSize;
    //   const end = start + this.pageSize;
    //   return this.stockChangeData.slice(start, end);
    // },
    HJFS () {
      // 过滤出 "大笔买入" 的股票
      const filteredStocks = this.stockChangeData.filter(stock => stock.changeType === "火箭发射");

      // 按 stockSymbol 进行分组
      let groups = filteredStocks.reduce((acc, item) => {
        const key = item.stockSymbol;
        if (!acc[key]) {
          acc[key] = {
            stockSymbol: item.stockSymbol,
            stockName: item.stockName,  // assuming first occurrence represents all occurrences
            count: 0
          };
        }
        acc[key].count += 1;
        return acc;
      }, {});

      // 转换对象为数组，并按照个数排序
      return Object.values(groups).sort((a, b) => b.count - a.count);
    },
    DBMR () {
      // 过滤出 "大笔买入" 的股票
      const filteredStocks = this.stockChangeData.filter(stock => stock.changeType === "大笔买入");

      // 按 stockSymbol 进行分组
      let groups = filteredStocks.reduce((acc, item) => {
        const key = item.stockSymbol;
        if (!acc[key]) {
          acc[key] = {
            stockSymbol: item.stockSymbol,
            stockName: item.stockName,  // assuming first occurrence represents all occurrences
            count: 0
          };
        }
        acc[key].count += 1;
        return acc;
      }, {});

      // 转换对象为数组，并按照个数排序
      return Object.values(groups).sort((a, b) => b.count - a.count);
    },
    KSFT () {
      // 过滤出 "大笔买入" 的股票
      const filteredStocks = this.stockChangeData.filter(stock => stock.changeType === "快速反弹");

      // 按 stockSymbol 进行分组
      let groups = filteredStocks.reduce((acc, item) => {
        const key = item.stockSymbol;
        if (!acc[key]) {
          acc[key] = {
            stockSymbol: item.stockSymbol,
            stockName: item.stockName,  // assuming first occurrence represents all occurrences
            count: 0
          };
        }
        acc[key].count += 1;
        return acc;
      }, {});

      // 转换对象为数组，并按照个数排序
      return Object.values(groups).sort((a, b) => b.count - a.count);
    }
  },
  methods: {
    formatDate (row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      let dt = new Date(data)
      function padZero (num) {
        return num.toString().padStart(2, '0');
      }

      // 使用padZero来格式化小时、分钟和秒
      let hours = padZero(dt.getHours());
      let minutes = padZero(dt.getMinutes());
      let seconds = padZero(dt.getSeconds());
      return hours + ':' + minutes + ':' + seconds;
    },
    formatData (row, column) {
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      if (data < 1) {
        return (data * 100).toFixed(2) + '%';
      } else {
        return (data / 100).toFixed(0) + '手';
      }
    },
    formatPrice (row, column) {
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      return (data / 1).toFixed(2);
    },
    handleSizeChange ( newSize) {
      this.pageSize = newSize;
      this.paginateData();
    },
    handleCurrentChange ( newPage) {
      this.currentPage = newPage;
      this.paginateData();
    },
    paginateData (data) {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      if (data == null) {
        data = this.stockChangeData;
      }
      this.paginatedData = data.slice(start, end);
    },
    handleStockChangeData () {

      // 将多选框中的数据格式变成 8192,8202,8204 
      const params = {
        changeType: this.checkList.join(',')  // 将数组转换为逗号分隔的字符串
      };

      this.$http.get('/stock/get-change-info', params).then(res => {
        if (res.data.code == 200) {
          this.stockChangeData = res.data.data;
          this.paginateData(this.stockChangeData);
        }
      });
    },

    startPolling () {
      this.stopPolling();  // 防止重复的定时器
      // Set an interval to check the time and execute a function if it's within the specified range
      this.timer = setInterval(() => {
        const currentTime = new Date();
        const currentHours = currentTime.getHours();
        const currentMinutes = currentTime.getMinutes();


        // 定义时间范围（9:30 到 15:00）
        const startHours = 9;
        const startMinutes = 30;
        const endHours = 15;
        const endMinutes = 0;

        // 将当前时间转换为分钟数
        const currentTotalMinutes = currentHours * 60 + currentMinutes;
        const startTime = startHours * 60 + startMinutes;
        const endTime = endHours * 60 + endMinutes;


        // Check if the current time is between 9:30 AM and 3:00 PM
        if (currentTotalMinutes >= startTime && currentTotalMinutes <= endTime) {
          this.handleStockChangeData(); // Call your function here
        }
      }, 20000); // Check every minute (60,000 milliseconds)
    },
    stopPolling () {
      if (this.timer) {
        clearInterval(this.timer);  // 清除定时器
        this.timer = null;
      }
    },
    handleChange () {
      this.handleStockChangeData();
    },
    handleQuery () {
      let searchData = this.stockChangeData.filter(stock =>
        stock.stockSymbol.includes(this.queryParams.stockName));
      this.paginateData(searchData);
    },
    resetQuery () {
      this.queryParams.stockName = ''
      this.paginateData(this.stockChangeData)
    }
  }
};
</script>

<style scoped>
.checkbox-group-container {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  max-width: 100%; /* 控制最大宽度以适应内容 */
  background-color: white; /* 设置背景颜色为白色 */
  padding: 10px; /* 添加内边距，使内容与边框有一定间隔 */
  margin-bottom: 10px;
  border: 1px solid #dcdfe6;
}

.checkbox-group .el-checkbox {
  width: 6%; /* 将checkbox分为两列 */
  box-sizing: border-box;
  padding: 5px;
}
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>